package com.bob.light.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.MotionEvent;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.core.content.ContextCompat;

import com.bob.light.R;

/**
 * @version 1.0.0
 * @author xhb
 * 格式化手机号码的输入框 带删除键
 */
public class FormatMobileEditText extends AppCompatEditText {
    private Drawable imgEnable;
    private Drawable imgAble;
    private final Context context;
    private boolean isLegalMobile = false;

    String PHONE_NUMBER_REG = "^(1)\\d{10}$" ;

    public FormatMobileEditText(Context context) {
        super(context);
        this.context = context;
        init();
    }

    public FormatMobileEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.context = context;
        init();
    }

    public FormatMobileEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        init();
    }

    public boolean isLegalMobile() {
        return isLegalMobile;
    }

    private boolean isMobile(Editable s) {
        if (TextUtils.isEmpty(s)) {
            return false;
        }
        return PHONE_NUMBER_REG.matches(formatEditableText(s));
    }

    /**
     * @return 格式化手机号码
     */
    private String formatEditableText(@Nullable Editable s) {
        if (TextUtils.isEmpty(s)) {
            return "";
        }
        assert s != null;
        return s.toString().replaceAll(" ","");
    }

    /**
     * @return 手机号码
     */
    public String getMobile() {
        return formatEditableText(getText());
    }

    public interface FormatMobileEditTextListener {
        void onTextChanged(CharSequence s);
    }
    FormatMobileEditTextListener mFormatMobileEditTextListener;
    public FormatMobileEditText setOnFormatMobileEditTextListener(FormatMobileEditTextListener formatMobileEditTextListener) {
        this.mFormatMobileEditTextListener = formatMobileEditTextListener;
        return this;
    }

    /********** 私有方法 **********/
    private void init() {
        imgEnable = ContextCompat.getDrawable(context, android.R.color.white);
        imgAble = ContextCompat.getDrawable(context, R.drawable.app_icon_edit_clear);
        addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s == null || s.length() == 0 || s.length() >= 13) return;
                StringBuilder sb = new StringBuilder(s.toString());
                if (before == 0){ //上一次是add时
                    if (sb.length() == 3 || sb.length() == 8){//自动追加空格
                        sb.append(' ');
                    }
                }
                if ((sb.length() == 4 || sb.length() == 9) && sb.charAt(sb.length()-1) != ' '){
                    sb.insert(sb.length() - 1, ' ');
                }

                if (!sb.toString().equals(s.toString())){
                    setText(sb.toString());
                    setSelection(sb.toString().length());
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                setDrawable();
                isLegalMobile = isMobile(s);
                if (mFormatMobileEditTextListener != null) {
                    mFormatMobileEditTextListener.onTextChanged(s);
                }
            }
        });
        setDrawable();
    }

    /**
     * 设置图片
     */
    private void setDrawable() {
        Drawable[] editDrawable = getCompoundDrawables();
        if (length() < 1) {
            setCompoundDrawablesWithIntrinsicBounds(editDrawable[0], editDrawable[1], imgEnable, editDrawable[3]);
        } else {
            setCompoundDrawablesWithIntrinsicBounds(editDrawable[0], editDrawable[1], imgAble, editDrawable[3]);
        }
    }

    @Override
    @SuppressLint("ClickableViewAccessibility")
    public boolean onTouchEvent(MotionEvent event) {
        if (imgAble != null && event.getAction() == MotionEvent.ACTION_UP) {
            int eventX = (int) event.getRawX();
            int eventY = (int) event.getRawY();
            Rect rect = new Rect();
            getGlobalVisibleRect(rect);
            rect.left = rect.right - 100;

            if (rect.contains(eventX, eventY)) {
                setText("");
            }
        }
        return super.onTouchEvent(event);
    }
}